package edu.rutgers.moko.data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import edu.rutgers.moko.data.util.Flag;
import edu.rutgers.moko.data.util.OMField;
import edu.rutgers.moko.data.util.PrivacyMode;
import edu.rutgers.moko.data.util.ProtectedAccess;

/**
 * 
 * @author Darja Krushevskaja
 * 
 */

public class FieldAccess implements Serializable {

	private static final long serialVersionUID = -7903237403968301918L;

	private OMField prop;

	private PrivacyMode privacyMode;

	private List<ProtectedRule> protectedRules = new ArrayList<ProtectedRule>();
	
	public void setValuesFromString(String ruleString){
		
		String[] ruleParsed = ruleString.split("\t");
		prop = OMField.getByField(ruleParsed[0]);
		privacyMode =PrivacyMode.getByField(ruleParsed[1]);
		if (privacyMode.equals(PrivacyMode.PROTECTED)) {
			String sub = ruleString.substring(ruleString.indexOf("{")+1, ruleString.length()-1);
			String[] attrs= sub.split(";");
			for (String attr : attrs) {
				protectedRules.add(parseRule(attr));
			}
			
		}
	}
	private ProtectedRule parseRule(String input){
		String[] parsed = input.split("\t");
		ProtectedRule pr = new ProtectedRule(ProtectedAccess.getByField(parsed[0]));
		pr.setFlag(Flag.getByTitle(parsed[1]));

		String[] ruleprops = parsed[2].split(":");
		switch (pr.getType()) {

		case LOCATION:

			pr.setX1(
					Integer.valueOf(ruleprops[0]));
			pr.setY1(
					Integer.valueOf(ruleprops[1]));
			pr.setX2(
					Integer.valueOf(ruleprops[2]));
			pr.setY2(
					Integer.valueOf(ruleprops[3]));
			break;

		case AP:
			pr.setApId(parsed[2]);
			break;
		case CLIENT:
			pr.setClientIp(ruleprops[0]);
			pr.setSubnetMask(ruleprops[1]);
			break;
		}
		return pr;
	}

	public PrivacyMode getPrivacyMode() {
		return privacyMode;
	}

	public void setPrivacyMode(PrivacyMode privacyMode) {
		this.privacyMode = privacyMode;
	}

	public List<ProtectedRule> getProtectedRules() {
		return protectedRules;
	}

	public void setProtectedRules(List<ProtectedRule> protectedRules) {
		this.protectedRules = protectedRules;
	}

	public OMField getProp() {
		return prop;
	}

	public void setProp(OMField prop) {
		this.prop = prop;
	}
	
	
	public void addProtectedRule(ProtectedRule pr){
		switch (privacyMode) {
		case PROTECTED:
			if(pr.isValid()){
				protectedRules.add(pr);
			}
			break;
		}
	}
	

	public String getFieldAccessAsRule() {
		StringBuilder rule = new StringBuilder();
		if(this.prop!=null){
			rule.append(this.prop.field()).append("\t");
		} else {
			rule.append("msg").append("\t");
		}
		rule.append(this.privacyMode.modelName()).append("\t");
		rule.append("{");
		for (ProtectedRule protectedRule : protectedRules) {
			rule.append(protectedRule.getAsRule());
		}
		rule.append("}");
		rule.append("\n");
		return rule.toString();
	}

}
